//
//  tklTools.m
//  wanyibeta
//
//  Created by wxt on 2019/1/28.
//  Copyright © 2019 wxt. All rights reserved.
//

#import "TKLTools.h"



@implementation TKLTools
//公钥加密
//+ (NSString *)RSAEncoderWithString:(NSString *)string {
//    //公钥  证书的描述信息
//    NSString *publicKey =pubkey;
//    
//    //RSA的加密(使用公钥)
//    //参数1, 想要加密的字符串
//    //参数2, 公钥
//    NSString *originStr = string;
//    NSString *secretStr = [RSA encryptString:originStr publicKey:publicKey];
//    
//    //转64
//    // [self base64WithString:secretStr]
//    
//    //  NSData *data12 = [secretStr dataUsingEncoding:NSUTF8StringEncoding];
//    // 2, Base64编码
//    // (1)返回值为字符串
//    //  NSString * encodeStr =  [self base64EncodeString:secretStr ];
//    
//    //    self.RSAstr = secretStr;
//    
//    return secretStr;
//    
//    
//}

+(NSDictionary *)deleNUllDic:(NSDictionary*)dic{
    NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] init];
    for (NSString *keyStr in dic.allKeys) {
     
        if ([[dic objectForKey:keyStr] isEqual:[NSNull null]]) {
     
            [mutableDic setObject:@"" forKey:keyStr];
        }
        else{
     
            [mutableDic setObject:[dic objectForKey:keyStr] forKey:keyStr];
        }
    }
    return mutableDic;
}

//解析网络上的数据
+(NSDictionary *)getDicFromResponse:(id)response{

    if ([response isKindOfClass:[NSData class]]) {
        return [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
    }
    if ([response isKindOfClass:[NSDictionary class]]) {
        return response;
    }
    return nil;
}
+(id)getValueFromDic:(NSDictionary *)dic withKey:(NSString *)key{
    for (NSString * miniKey in dic) {
        if ([miniKey isEqualToString:key]) {
            return dic[key];
        }
    }
    return nil;
}



// 异或密码加密
+ (NSString *)encryptPassword:(NSString *)password key:(NSString *)key
{
    password = [password stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *encryptPassword = @"";
    for (NSInteger i = 0; i < password.length; i ++) {
        unichar unichar = [password characterAtIndex:i] ^ [key intValue];
        NSString *string = [NSString stringWithFormat:@"%C", unichar];
        encryptPassword = [NSString stringWithFormat:@"%@%@", encryptPassword, string];
    }
    encryptPassword = [[encryptPassword dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
    
//    CocoaSecurityEncoder *encoder = [CocoaSecurityEncoder new];
//    CocoaSecurityResult *encrypt = [CocoaSecurity aesEncrypt:password hexKey:[encoder hex:[key dataUsingEncoding:NSUTF8StringEncoding] useLower:NO] hexIv:@"00000000000000000000000000000000"];
//    NSString *encryptPassword = encrypt.base64;
//
//    NSLog(@"password:%@,key:%@,encryptPassword:%@", password, key, encryptPassword);
    
    return encryptPassword;
}

//字典转字符串
+ (NSString *)conversionDictionary:(NSDictionary *)dic

{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}



+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    
  
    
    NSString *MOBILE = @"^1(3[0-9]|4[5-9]|5[0-35-9]|6[25-7]|7[0-9]|8[0-9]|9[025-9])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
    
    
    
}
+(BOOL)isPassWord:(NSString * )passWord{
//    ^(?=.*[0-9]+)(?=.*[a-z]+)(?=.*[A-Z]+)(?=.*[#?!@$%^&*]+)([\\w#?!@$%^&*]){8,16}$
    
    NSString * passWordstr=@"^(?=.*[0-9]+)(?=.*[a-z]+)(?=.*[A-Z]+)([\\w#?!@$%^&*]){8,16}$";
    
    NSPredicate *upperPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordstr];

    return  [upperPred evaluateWithObject:passWord];
  
}
+ (BOOL)stringContainsEmoji:(NSString *)string {
    
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        if (0x278b <= hs && hs <= 0x2792) {
                                            //自带九宫格拼音键盘
                                            returnValue = NO;;
                                        }else if (0x263b == hs) {
                                            returnValue = NO;;
                                        }else {
                                            returnValue = YES;
                                        }
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}
+ (float)getDistance:(float)lat1 lng1:(float)lng1 lat2:(float)lat2 lng2:(float)lng2
{
    //地球半径
    int R = 6378137;
    //将角度转为弧度
    float radLat1 = [self radians:lat1];
    float radLat2 = [self radians:lat2];
    float radLng1 = [self radians:lng1];
    float radLng2 = [self radians:lng2];
    //结果
    float s = acos(cos(radLat1)*cos(radLat2)*cos(radLng1-radLng2)+sin(radLat1)*sin(radLat2))*R;

    //精度
    s = s/1000;
    return  s;
}
+ (float)radians:(float)degrees{
    return (degrees*3.14159265)/180.0;
}
+(NSString *)toRoman:(int)num {
    NSString *roman = @"";
    if (num > 0 && num < 100) {
        
        NSArray *pChars = [[NSArray alloc]initWithObjects: @"L", @"X", @"V", @"I", nil];
        NSArray *pValues = [[NSArray alloc]initWithObjects:@"50",@"10" , @"5", @"1" , nil];
        
        
        while (num > 0) {
            if (num >= 90) {
                roman = [roman stringByAppendingString:@"XC"];
                num -= 90;
                continue;
            }
            
            if (num >= [[pValues objectAtIndex:0] intValue]) {
                NSString *string = [NSString stringWithFormat:@"%@",[pChars objectAtIndex:0]];
                roman = [roman stringByAppendingString:string];
                num -= [[pValues objectAtIndex:0] intValue];
                continue;
            }
            if (num >= 40) {
                roman = [roman stringByAppendingString:@"XL"];
                
                num -= 90;
                continue;
            }
            if (num >= [[pValues objectAtIndex:1] intValue]) {
                int x10 = num /[[pValues objectAtIndex:1] intValue];
                for (int i = 0; i < x10; i++) {
                    
                    NSString *string = [NSString stringWithFormat:@"%@",[pChars objectAtIndex:1]];
                    roman = [roman stringByAppendingString:string];
                    num -= [[pValues objectAtIndex:1] intValue];
                }
                continue;
            }
            if (num >= 9) {
                roman = [roman stringByAppendingString:@"IX"];
                
                num -= 9;
                continue;
            }
            if (num >= [[pValues objectAtIndex:2] intValue]) {
                
                NSString *string = [NSString stringWithFormat:@"%@",[pChars objectAtIndex:2]];
                roman = [roman stringByAppendingString:string];
                
                num -= [[pValues objectAtIndex:2] intValue];
                continue;
            }
            if (num == 4) {
                roman = [roman stringByAppendingString:@"IV"];
                num = 0;
                continue;
            }
            for (int i = 0; i < num; i++) {
                
                NSString *string = [NSString stringWithFormat:@"%@",[pChars objectAtIndex:3]];
                roman = [roman stringByAppendingString:string];
                
                num -= [[pValues objectAtIndex:3] intValue];
            }
        }
        
        
    } else {
        NSLog(@"数字超出范围！");
    }
    
    return roman;
}

+(NSString *)getMMSSFromSS:(NSString *)totalTime{

    NSInteger seconds = [totalTime integerValue];

    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];

  

    return format_time;

}
+ (NSString *)arrayToJSONString:(NSArray *)array

 {
    if ([array isKindOfClass:[NSString class]]) {
           return (NSString *)array;
       }
       NSError *parseError = nil;
       NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
       NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
       jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
       jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
       jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
       if (parseError) {
           jsonStr = @"";
       }
       return jsonStr;
}


+(NSString *)obfuscate:(NSString *)string withKey:(NSString *)key
{
    
    
    NSLog(@"%@,%@",string,key);
       NSData * bytes = [string dataUsingEncoding:NSUTF8StringEncoding];
    
       Byte * myByte = (Byte *)[bytes bytes];
    
       NSData * keyBytes = [key dataUsingEncoding:NSUTF8StringEncoding];
    
       Byte*keyByte = (Byte *)[keyBytes bytes];
        
       int keyIndex = 0;
    
       for (int x = 0; x < [bytes length]; x++)
       {
           
         myByte[x] = myByte[x] ^ keyByte[keyIndex];

//             if (++keyIndex == [keyBytes length])
//            {
//                keyIndex = 0;
//             }
        }


//可以直接返回NSData
NSData *newData = [[NSData alloc] initWithBytes:myByte length:[bytes length]];
NSString *aString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];

return aString;

}
+ (id)jwtDecodeWithJwtString:(NSString *)jwtStr {
    
    NSArray * segments = [jwtStr componentsSeparatedByString:@"."];
    NSString * base64String = [segments objectAtIndex:1];
    
    int requiredLength = (int)(4 *ceil((float)[base64String length]/4.0));
    int nbrPaddings = requiredLength - (int)[base64String length];
    if(nbrPaddings > 0) {
        NSString * pading = [[NSString string] stringByPaddingToLength:nbrPaddings withString:@"=" startingAtIndex:0];
        base64String = [base64String stringByAppendingString:pading];
    }
    base64String = [base64String stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
    base64String = [base64String stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
    NSData * decodeData = [[NSData alloc] initWithBase64EncodedData:[base64String dataUsingEncoding:NSUTF8StringEncoding] options:0];
    NSString * decodeString = [[NSString alloc] initWithData:decodeData encoding:NSUTF8StringEncoding];
    NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:[decodeString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    return jsonDict;
}

+(NSDateComponents *)compntDate:(NSString *)staDateStr withDate:(NSString*)endDateStr{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *startDate = [dateFormatter dateFromString:staDateStr];
    NSDate *endDate = [dateFormatter dateFromString:endDateStr];

    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传：
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    //打印
//    NSLog(@"%@",delta);
//    //获取其中的"天"
//    NSLog(@"%ld",delta.day);
    
    
    return delta;
    
    
    
}
+(NSString *)getNomeTimeData{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
        NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
        NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
        return timeString;
    
}
+(NSString *)getNomeTime{
    
    NSDate *date = [NSDate date];
       //使用formatter格式化后的时间

       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

       [formatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];//样式

       NSString *time_now = [formatter stringFromDate:date];
    
    
    return time_now;
}
+(NSString *)strFirstBig:(NSString*)str{
    NSString *resultString = @"";
    if (str.length > 0) {
        resultString = [str stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[str substringToIndex:1] capitalizedString]];
    }
    return resultString;
    
}
@end
